package org.microframework.cloud.auth.service;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.microframework.base.core.constant.SecurityConstants;
import org.microframework.base.core.domain.R;
import org.microframework.base.model.system.dto.SecurityUser;
import org.microframework.base.feign.system.RemoteUserService;

/**
 * 用户详情服务 等保要求：实现用户身份认证
 */
@Service
@Slf4j
public class SecurityUserDetailsService implements UserDetailsService {

	@Autowired
	private RemoteUserService remoteUserService;

	/**
	 * 根据用户名加载用户 等保要求：应记录用户认证日志，包括认证成功和失败的情况
	 */
	@Override
	//@Transactional(readOnly = true)
	//@Tx
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		try {
			R<SecurityUser> r = remoteUserService.loadUserByUsername(username, SecurityConstants.INNER);
			if (200 == r.getCode()) {
				SecurityUser securityUser = r.getData();
				return new User(securityUser.getUsername(), securityUser.getPassword(), 
						Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
			} else {
				throw new UsernameNotFoundException("用户不存在: " + username);
			}
		} catch (Exception e) {
			log.error("用户[{}]登录失败: {}", username, e.getMessage());
			throw e;
		}
	}
}